// 授权的云函数
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const taskCollection = db.collection('task')
const TcbRouter = require('tcb-router');

// 云函数入口函数
exports.main = async (event, context) => {
	let app = new TcbRouter({event})
	const {OPENID} = cloud.getWXContext()
	app.router('save',async (ctx,next)=>{
		let {name,labellist,squadid} = event;
		ctx.body = taskCollection.add({
			data: {
				name,
				labellist,
				squadid,
				state: 0,
				openid: OPENID,
				createTime: Date.now()
			}
		})
	})
	app.router('getListOpenId',async  (ctx,next)=>{
		const _ = db.command
		let {pageNum=1,pageSize=1000,squadid} = event;
		ctx.body = taskCollection
		.skip((pageNum-1)*pageSize)
		.limit(pageSize)
		.where({
			squadid: _.in(squadid)
		})
		.orderBy('createTime','desc')
		.get()
	})
	app.router('list',async (ctx,next)=>{
		let {pageNum,pageSize,content,squadid} = event;
		content = content.trim()
		var w = {}
		if(content!==''){
			w = {
				content: db.RegExp({
					regexp: content,
					options: 'i'
				}),
				squadid
			}
		}
		ctx.body = await taskCollection
			.where(w)
			.skip((pageNum-1)*pageSize)
			.limit(pageSize)
			.orderBy('createTime','desc')
			.get()
			.then(res=>res);
	})
	app.router('cancelTasks',async (ctx,next)=>{
		let {id} = event;
		ctx.body = await taskCollection
			.where({
				_id: id
			})
			.update({
				data: {
					state: 1,
				}
			})
			.then(res=>res);
	})
	
	app.router('detail',async (ctx,next)=>{
		let {id} = event;
		ctx.body = await taskCollection
			.where({
				_id: id
			})
			.get()
			.then(res=>res.data[0]);
	})
	return app.serve()
}